package com.ratingbay.console.social;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.social.DuplicateStatusException;
import org.springframework.social.connect.Connection;
import org.springframework.social.connect.UserProfile;
import org.springframework.social.connect.web.SignInAdapter;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.savedrequest.RequestCache;
import org.springframework.security.web.savedrequest.SavedRequest;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;

import com.ratingbay.console.common.RatingBayConst;
import com.ratingbay.console.utils.CookieUtil;

public class SimpleSignInAdapter implements SignInAdapter {

    protected Logger logger = LogManager.getLogger(this.getClass().getName());
    
    public String signIn(String userId, Connection<?> connection, NativeWebRequest request) {

        SecurityContextHolder.getContext().setAuthentication(new UsernamePasswordAuthenticationToken(userId, null, null));

        connection.sync();
        UserProfile profile = connection.fetchUserProfile();
        String userName = profile.getUsername();
        String email = profile.getEmail();
        String url=null;
        boolean status = SigninHelper.getInstance().signin(userName, email);
        HttpServletRequest req =  request.getNativeRequest(HttpServletRequest.class);
        boolean f=false;
        Cookie[] cookies=req.getCookies();
        for(Cookie c:cookies){
        	if("rt_willingTweetRB".equals(c.getName())){
        		f=true;
        	}
        	if("ratingbayPostSignInUrl".equals(c.getName())){
        		try{
        			url=URLDecoder.decode(c.getValue(),"UTF-8");
        		}catch(UnsupportedEncodingException e){
        			System.out.println("postSignInUrl decode flase");
        		}
        	}
        }
        if(f){
            try {
    			connection.updateStatus("I'm using http://ratingbay.com/user/"+userName+" to see what my friends say about games. Check it out http://ratingbay.com");
    		} catch (DuplicateStatusException e) {
    		}
        }
        //init user data for logined twitter user
        TwitterUserSignin.getInstance().initUserData(connection, profile);
        /*
        HttpServletRequest req=(HttpServletRequest)request;
        CookieUtil.checkCookie(req, request.getNativeResponse(HttpServletResponse.class), RatingBayConst.COOKIE_ID);
        */
        if(status){
        	//signin success
        return url;
        }else{
           //signin false
           return null;
        }
    }
}
